<!-- 父组件 -->
<template>
  <div>
    <todoHeader @bood="bood" />
    <TodoItem
      :todos="todos"
      :comitems="comitems"
      @removeTodo="removeTodo"
      @setCurrentTodo="setCurrentTodo"
      @over="over"
    />
    <gitee />
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import todoHeader from "./todoHeader.vue";
import TodoItem from "./todoItem.vue";
import gitee from "./gitee.vue";

// 声明comitems和todos
const comitems = ref([]);
const todos = ref([]);

const bood = (list) => {
  todos.value.push(list);
  localStorage.setItem("todos", JSON.stringify(todos.value));
};

//  删除待办事项
const removeTodo = (index) => {
  let Delete = window.confirm("您是否确认要删除" + todos.value[index] + "吗？");
  if (Delete) {
    todos.value.splice(index, 1);
  }
  localStorage.setItem("todos", JSON.stringify(todos.value));
};

// 完成待办事项
const setCurrentTodo = (todo) => {
  const index = todos.value.findIndex((i) => i === todo);
  if (index !== -1) {
    todos.value.splice(index, 1)[0];
  }
  comitems.value.push(todo);
  localStorage.setItem("todos", JSON.stringify(todos.value));
  localStorage.setItem("item", JSON.stringify(comitems.value));
};

// 接收comitem
const comitem = (index) => {
  const comitem = todos.value.splice(index, 1)[0];
  comitems.value.push(comitem);
};

// 清空本地存储
const over = () => {
  comitems.value = comitems.value.filter((todo) => !todo);
  localStorage.removeItem("item", JSON.stringify(comitems.value));
};

// 组件挂载时加载数据
onMounted(() => {
  const a = JSON.parse(localStorage.getItem("todos"));
  if (localStorage.getItem("todos")) {
    todos.value = JSON.parse(localStorage.getItem("todos"));
  }
  const c = JSON.parse(localStorage.getItem("item"));
  if (localStorage.getItem("item")) {
    comitems.value = JSON.parse(localStorage.getItem("item"));
  }
});
</script>
